package jnpf.base.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import jnpf.database.source.DbBase;
import jnpf.database.util.*;
import jnpf.util.StringUtil;
import jnpf.util.data.DataSourceContextHolder;

/**
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2021/3/12 15:31
 */
public class SourceUtil {

    public static DataSourceConfig dbConfig(String dbName, DataSourceUtil linkEntity) {
        if (linkEntity == null) {
            if(TenantDataSourceUtil.isTenantAssignDataSource()){
                linkEntity = TenantDataSourceUtil.getTenantAssignDataSource(DataSourceContextHolder.getDatasourceId()).toDbLinkEntity();
            }else{
                linkEntity = DynamicDataSourceUtil.dataSourceUtil.init();
            }
            if (!"PostgreSQL".equals(linkEntity.getDbType()) && StringUtil.isNotEmpty(dbName)) {
                linkEntity.setDbName(dbName);
            }
        }
        DataSourceConfig dsc = new DataSourceConfig();
        try {
            DbBase dbBase = DbTypeUtil.getDb(linkEntity);
            dsc.setDbType(dbBase.getMpDbType());
            dsc.setDriverName(dbBase.getDriver());
            dsc.setUsername(linkEntity.getUserName());
            dsc.setPassword(linkEntity.getPassword());
            dsc.setSchemaName(linkEntity.getDbSchema());

            // oracle 默认 schema = username
            if (dbBase.getMpDbType().toString().equalsIgnoreCase(DbType.ORACLE.getDb())) {
                dsc.setSchemaName(linkEntity.getUserName());
            }

            dsc.setUrl(ConnUtil.getUrl(linkEntity));
        } catch (Exception e) {
            e.getStackTrace();
        }
        return dsc;
    }

}
